package cn.org.qary.controller.abelianymph.front;

import cn.org.qary.entity.Product;
import cn.org.qary.service.trait.abelianymph.ProductService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Controller
@RequestMapping("product")
public class ProductController {

    @Autowired
    ProductService productService;

    @RequestMapping("like/{keyword}/{page}")
    public String like(
            @PathVariable String keyword,
            @PathVariable(required = false) Integer page,
            RedirectAttributes attributes) {
        Page<Object> objectPage = PageHelper.startPage(page, 6);
        List<Product> productList = productService.searchByKeyWord(keyword);
        attributes.addFlashAttribute("page", objectPage);
        attributes.addFlashAttribute("productList", productList);
        attributes.addFlashAttribute("keyword", keyword);
        return "redirect:/product/here";
    }

    @RequestMapping("search")
    public String search(String id, Model model) {
        Product product = productService.selectById(id);
        System.out.println(product);
        model.addAttribute("product", product);
        return "productview";
    }

    @RequestMapping("add_to_cart")
    public String addToCart(String productId, String amount) {

        return String.format("redirect:/cart/add?productId=%s&amount=%s", productId, amount);
    }

    @RequestMapping("here")
    public String here() {
        return "list";
    }

    /**
     * 查询商品显示在首页
     */
    @RequestMapping("find")
    @ResponseBody
    public List<Product> find() {
        List<Product> list = productService.selectAll();
        return list;
    }

    /**
     * 根据二级分类id查找商品
     * @param id 要查找的二级分类id
     * @param model 向list.jsp转发数据
     * @param page 分页参数
     * @return 跳转到list.jsp
     */
    @RequestMapping("secondaryType/{id}/{page}")
    public String searchBySecondaryTypeId(
            @PathVariable Integer id,
            Model model,
            @PathVariable Integer page) {
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("secondaryTypeId", id);

        Page<Object> objectPage = PageHelper.startPage(page, 6);
        List<Product> productList = productService.selectByCondition(example);

        model.addAttribute("page", objectPage);
        model.addAttribute("productList", productList);

        return "list";

    }

}
